#!/usr/bin/python

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or (at
#  your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import sys
import math
from pyqt4 import *
import time
import os

from controlpart import *
from plotpart import *
from savepart import *
from aboutbox import *
from visatester import *
from superbatchmode import *

#
# in pyvlab.py are all main-classes of pyvlab
# 
# Classes: 	mainWindow:	creates the 3 parts, plotpart, controlpart and savepart
#


class mainWindow(QMainWindow):
	def __init__(self,s=None,parent=None,name=None):
		QMainWindow.__init__(self,parent)
	
	
        	self.setCentralWidget(QWidget(self,"qt_central_widget"))
        	MainFormLayout = QGridLayout(self.centralWidget(),1,1,11,6,"MainForm1Layout")

        	self.conf=mainWriteReadConf(self.centralWidget())
		self.measureplot = measurePlot(self.centralWidget())
		self.save = saveClass(self.centralWidget())
	
		self.superbatch=superbatchmode(self)
	
		#self.connect(self.measureplot,PYSIGNAL('newMessdaten'),self.ivtesterconf.extractNewMessdaten)
		self.connect(self.conf,PYSIGNAL('newMessdaten'),self.measureplot.newMessdaten)
		self.connect(self.conf,PYSIGNAL('newMessung'),self.measureplot.newMessung)
		self.connect(self.conf,PYSIGNAL('endMessung'),self.save.endMessung)
		self.connect(self.conf,PYSIGNAL('endBatchMessung'),self.endBatchMessung)
		self.connect(self.conf,PYSIGNAL('stopMessung'),self.stopMessung)
		self.connect(self.conf,PYSIGNAL('startMessung'),self.startMessung)
	
	
		self.connect(self.save,PYSIGNAL('reqMessdaten'),self.measureplot.emitAllMessdaten)	
		self.connect(self.measureplot,PYSIGNAL('emitAllMessdaten'),self.save.speichere)
		self.connect(self.measureplot,PYSIGNAL('nextMessdaten'),self.save.nextData)
		self.connect(self.save,PYSIGNAL('dataSaved'),self.dataSaved)
		self.connect(self.superbatch,PYSIGNAL('autoMeasureFile'),self.autoMeasureFile)
		self.connect(self.superbatch,PYSIGNAL('stopMeasure'),self.conf.stop)
		
		menubar = QMenuBar(self)
		filemenu = QPopupMenu(self)
		self.fileName=""
		filemenu.insertItem("&New",self.fileNew,Qt.CTRL+Qt.Key_N)
		filemenu.insertItem("&Open",self.fileOpen,Qt.CTRL+Qt.Key_O)
		filemenu.insertItem("&Save",self.fileSave,Qt.CTRL+Qt.Key_S)
		filemenu.insertItem("Save &as",self.fileSaveas)
		filemenu.insertSeparator()
		
		filemenu.insertItem("&Exit",self,SLOT("close()"))# qApp, SLOT( "quit()" ))#self.FileExit)
		
		visamenu = QPopupMenu(self)
		visamenu.insertItem("&VisaTester",self.visaTester)
		visamenu.insertItem("&SuperBatchMode",self.SuperBatchMode)
		
		helpmenu = QPopupMenu(self)
		helpmenu.insertItem("&About",self.aboutBox)
		
		menubar.insertItem( "&File", filemenu )
		menubar.insertItem( "&Visa", visamenu )
		menubar.insertItem( "&Help", helpmenu )
		#menubar.setSeparator( QMenuBar.InWindowsStyle )

        	#l = QVBoxLayout(self.centralWidget())
		MainFormLayout.setSpacing(0)
		MainFormLayout.setMargin(0)
	
		MainFormLayout.addWidget(self.measureplot,0,0)
		MainFormLayout.addWidget(self.conf,1,0)
		MainFormLayout.addWidget(self.save,2,0)
		
		self.statusbar=QStatusBar(self.centralWidget())
		MainFormLayout.addWidget(self.statusbar,3,0)
		
		self.openFile("autosave.pyv",False,True)
		self.statusbar.message("pyvLab loaded...",3000)
	
		
	def visaTester(self):
		vt=visatester(self)
		#clear internal devices...because they loose their gpib handle if a new one with visatester was opened
		self.conf.visa.devices=[]
		vt.show()
		
	def aboutBox(self):
		ab=aboutBox(self)
		ab.show()

	def fileNew(self):
		self.fileName=""
		self.conf.new()
		
		
	def openFile(self,file,loadDeviceSettings=True,loadBaseSaveFile=False):
		s=unicode(file)
		fi=QFileInfo()
		fi.setFile(s)
		#print s
		
		if fi.exists()==True:
			f = open(s, 'r')
			try:
				sav=pickle.load(f)
				
				if loadDeviceSettings==True:
					self.conf.load(sav) #Load last config

				if loadBaseSaveFile==True:
					if sav[len(sav)-2][0]=="basefile":
						self.save.datei.setText(sav[len(sav)-2][1])
					if sav[len(sav)-1][0]=="fileextension":
						self.conf.setCombo(self.save.dateiendung,unicode(sav[len(sav)-1][1]))

				self.statusbar.message("file loaded...",13000)
			except:
				QMessageBox.critical( None, "pyvLab", "ERROR: Could not load file "+s)
				#print s
				f.close()
			else: 	f.close()
			
					
	def fileOpen(self):
		s=""
		s = QFileDialog.getOpenFileName("","All File (*.pyv)",self,"File To Open","File To Open" )
		s=unicode(s)
		if len(s)>0:
			self.openFile(s)
			self.fileName=s

		
	def fileSave(self):
		if len(self.fileName)==0:
			self.fileSaveas()
			return
		
		#print "save"
		test=os.path.split(self.fileName)
		if len(test[0])>0:
			if os.path.isdir(test[0])==False:
				QMessageBox.critical( self, "pyvLab", "ERROR: Directory to save in does not exist. Nothing saved.")
				return False
		
		f = open(self.fileName, 'w')
		sav=self.conf.save()
		sav.append( ("basefile",unicode(self.save.datei.text())) )
		sav.append( ("fileextension",unicode(self.save.dateiendung.currentText())) )
		#f.write(str(sav))
		pickle.dump(sav, f)
		f.close()
		self.statusbar.message("file saved...",13000)

	def fileSaveas(self):
		#print "saveas"
		s = QFileDialog.getSaveFileName("","All File (*.pyv)",self,"File To Save","File To Save" )
		s=unicode(s)
		if s[-4:]!=".pyv":
			s=s+".pyv"
			
		#doesn't work on win32
		#fi=QFileInfo()
		#fi.setFile(s)
		#print "x",s
		#if fi.exists()==True:
		#	mb = QMessageBox( "File exists","File exists, overwrite?",QMessageBox.NoIcon,QMessageBox.Yes | QMessageBox.Default, QMessageBox.Cancel | QMessageBox.Escape, QMessageBox.NoButton )
    		#	#print "x",s
		#	if (mb.exec_loop()==QMessageBox.Cancel):
		#		return False

		if len(s)>4:
			self.fileName=s
			self.fileSave()

	
	def dataSaved(self,fileName):
		self.statusbar.message("single measurement saved to "+unicode(fileName))
		
	def endBatchMessung(self):
		#self.statusbar.message("all measures finished...")
		self.superbatch.nextFile()
		
	def stopMessung(self):
		self.statusbar.message("measuring stopped...")
		
	def startMessung(self):
		self.statusbar.message("measuring startet...")


	def autoMeasureFile(self,file):
		#print "start",file
		self.fileName=file
		self.openFile(file)
		self.conf.start()
		
	def SuperBatchMode(self):
		self.superbatch.show()
		
	def closeEvent(self,ce):
		#print "Closing"
		tmp=self.fileName
		self.fileName="autosave.pyv"
		self.fileSave()
		self.fileName=tmp

		ce.accept()


QApplication.setColorSpec(QApplication.CustomColor)
a = QApplication(sys.argv)

gb = mainWindow()
#gb.setGeometry(100,100,700,800)
gb.resize(600,700)
a.setMainWidget(gb)
gb.show()
gb.setCaption("pyvLab (Version 1.3)")
a.exec_loop()
